import MySQLdb

class Chunker: 

  mysqldb = "twitter"
  counttable = "chunks"
  twittertable = "statuses"
  mysqluser = "root"
  chunk_size = "600" # in seconds

  def update(self):
     # Go through everything in the database
     # and add new records for time periods that aren't covered.
     # Currently hacky: assumes coverage is block up to last entry
     # i.e. entries before last created_at are all covered
     # and we only need to count 'new' ones.
     # Proper implementation: check for any gaps. (Ouch.)

     db = MySQLdb.connect(db=self.mysqldb, user=self.mysqluser)
     cursor = db.cursor()

     # SQL translated: "Get the most recent entry, i.e. highest end."
     sql_query = "SELECT * FROM %s ORDER BY end DESC LIMIT 1" % self.counttable

     cursor.execute(sql_query)
     row = cursor.fetchone()

     if (row != None): 
       # Pull out the info from this latest entry
       # Isn't it tempting to use django or something now...
       last_start = row[1]
       last_end = row[2]
       last_count = row[3]
       print last_start, last_end, last_count
     else:
       # Get the first ever entry and start there ^_^
       sql_query = "SELECT * FROM %s LIMIT 1" % self.twittertable
       cursor.execute(sql_query)
       row = cursor.fetchone()
       last_end = row[1] # created_at_in_seconds
       last_count = 0
       last_start = 0
       print last_start, last_end, last_count
     
     self.update_period(600, last_end, cursor)

     cursor.close()
     self.updated = "true" 

  def update_period(self,duration,start,cursor):
     # Duration expected in SECONDS
     # Count items in twittertable with created_at between start and start+duration.
     # Insert result into counttable.

     sql_query = "SELECT COUNT('id') from %s WHERE created_at_in_seconds >= %s AND created_at_in_seconds < %s" % (self.twittertable, start, start+duration)
    
     cursor.execute(sql_query)
     row = cursor.fetchone()
     print row[0]
   
     # now insert that value
     sql_query = "INSERT INTO %s (start,end,count) VALUES (%s,%s,%s)" % (self.twittertable, start, start+duration, row[0])
     print sql_query



  def return_period(self, start):
     return "20"

  def return_all(self):
     return "40"
